import Vue from 'vue'
import Router from 'vue-router'
import Cookies from "js-cookie"

import home from '@/pages/home.vue'
import login from '@/pages/login.vue'
import findPassword from '@/pages/findPassword.vue'
import notFound from '@/pages/404/404.vue'
import store from '@/store'
import { inArray } from '../utils/array.js'

Vue.use(Router)

const staticRoute = [{
    // 首页
    path: '/home',
    component: home,
    meta: {
      title: '首页'
    },
    children: []
  },
  {
    // 首页
    path: '/',
    redirect:'/home'
  },
  {
    // 登录页
    path: '/login',
    name: 'login',
    component: login,
    meta: {
      title: '欢迎登录'
    }
  },
  {
    // 找回密码页
    path: '/findPassword',
    name: 'findPassword',
    component: findPassword,
    meta: {
      title: '找回密码'
    }
  },
  {
    path: "/404",
    component: notFound,
    meta: {
      title: '页面走丢了···'
    }
  },
  //如果是动态多级路由，需要去掉这个
  {
    path: "*",
    component: notFound,
    meta: {
      title: '页面走丢了···'
    }
  }
]


const router = new Router({
  mode: "history",
  routes: staticRoute
});
const noLogin=[
  '/findPassword','/404'
]
router.beforeEach((to, from, next) => {
  // 登录界面登录成功之后，会把用户信息保存在会话
  // 存在时间为会话生命周期，页面关闭即失效。
  let token = Cookies.get('token')
  let userName = sessionStorage.getItem('user')
  if (to.path === '/login') {
    // 如果是访问登录界面，如果用户会话信息存在，代表已登录过，跳转到主页
    if (token) {
      next({
        path: '/'
      })
    } else {
      next()
    }
  } else {
    if (!token&&!inArray(noLogin,to.path) ) {
      // 如果访问非登录界面，且户会话信息不存在，代表未登录，则跳转到登录界面
      next({
        path: '/login'
      })
    }else if(!token&&inArray(noLogin,to.path)){
      next()
    }
     else {
      // 加载动态菜单和路由(因为我已经用tab实现了一级路由,这里就不需要了)
      //addDynamicMenuAndRoutes(userName, to, from)
      next()
    }
  }
})

//动态添加路由和菜单
function addDynamicMenuAndRoutes() {
  if (store.state.menu.menuRouteLoaded) {
    console.log('动态菜单和路由已经存在!')
    return
  }

  let dynamicRoutes = addDynamicRoutes(store.state.menu.menu)
  //所有路由全部放进首页的子路由里
  router.options.routes[0].children = router.options.routes[0].children.concat(dynamicRoutes)

  //404放在最后面
  router.options.routes=router.options.routes.concat({
    path:"*",
    name:"notFound",
    component: notFound
  })

  //添加路由,会产生重复的路由,不影响使用，vue-router会自动去重
  router.addRoutes(router.options.routes)
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function addDynamicRoutes(menuList = [], routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    //是否有子菜单
    if (menuList[i].children && menuList[i].children.length >= 1) {
      temp = temp.concat(menuList[i].children) //将子菜单组成一个新数组
    }
    if (menuList[i].url && /\S/.test(menuList[i].url))//如果路径不为空
     {
      menuList[i].url = menuList[i].url.replace(/^\//, '')
      // 创建路由配置
      let route = {
        path: menuList[i].url,
        component: null,
        name: menuList[i].name,
        meta: {
          icon: menuList[i].icon,
          index: menuList[i].id
        }
      }
      try {
        // 根据菜单URL动态加载vue组件，这里要求vue组件须按照url路径存储
        // 如url="sys/user"，则组件路径应是"@/pages/sys/user.vue",否则组件加载不到
        let array = menuList[i].url.split('/')
        let url = ''
        for (let i = 0; i < array.length; i++) {
          url += array[i].substring(0, 1).toLowerCase() + array[i].substring(1) + '/'
        }
        url = url.substring(0, url.length - 1)
        route['component'] = resolve => require([`@/pages/${url}`], resolve)
      } catch (e) {}

      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    //添加子菜单的路由
    addDynamicRoutes(temp, routes)
  } else {
    console.log('动态路由加载完成.')
  }
  return routes
}


export default router
